package com.xgq.drink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.UserBehavior;
import com.xgq.drink.mapper.*;
import com.xgq.drink.service.ICategoryService;
import com.xgq.drink.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xgq
 * @since 2025-02-23
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Override
    public IPage<Product> getProductList(Page<Product> page) {
        // 查询部分字段
        return baseMapper.selectPage(page, null);
    }
    @Autowired
    private ProductMapper productMapper;
    @Override
    public int logicDeleteProduct(Long productId, Long brandId) {
        return productMapper.logicDeleteById(productId, brandId);
    }
    @Override
    public IPage<Product> getProductListByCategory(Page<Product> page, Long categoryId) {
        // 调用 ProductMapper 的分页查询方法
        return baseMapper.selectPageByCategory(page, categoryId);
    }
    @Override
    public IPage<Product> getProductListByBrandId(Page<Product> page, Long brandId) {
        // 创建 QueryWrapper 并添加条件
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id", brandId)
                .ne("is_del", 1)// 添加 is_del != 1 的条件
                .orderByDesc("updated_at");
        // 调用 ProductMapper 的分页查询方法
        return baseMapper.selectPage(page, queryWrapper);
    }
    public int updateProduct(Product product) {
        product.setUpdatedAt(LocalDateTime.now());
        int maxAttempts = 3; // 最大尝试次数
        int attempts = 0; // 当前尝试次数

        while (attempts < maxAttempts) {
            attempts++;
            System.out.println("Version"+product.getVersion());
            if (this.updateById(product)) {
                return 1;
            } else {
                // 如果更新失败，版本号+1
                product.setVersion(product.getVersion() + 1);
            }
        }
        return 0;
    }
    @Override
    public boolean existsProduct(Long productId) {
        return this.lambdaQuery()
                .eq(Product::getProductId, productId)
                .exists();
    }

    @Override
    public Product getProductDetailById(Long productId) {
        // 查询全部字段
        return baseMapper.selectById(productId);
    }
    @Override
    public boolean saveProductWithAttributes(Product product) {
        return this.save(product);
    }
    // 在 ProductServiceImpl 中的实现示例
    public IPage<Product> getProductListWithConditions(Page<Product> page, String productName,
                                                       Double minPrice, Double maxPrice, Long categoryId) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(productName)) {
            wrapper.like("name", productName);
        }
        if (minPrice != null && maxPrice != null) {
            wrapper.between("price", minPrice, maxPrice);
        }
        if (categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }

        return baseMapper.selectPage(page, wrapper);
    }

    public IPage<Product> getBrandProductsWithConditions(
            Page<Product> page, Long brandId, String productName,
            Long productId, Long categoryId, Double minPrice, Double maxPrice, LocalDateTime updateTime) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        if (brandId!=null) {
            wrapper.eq("brand_id", brandId);
        }
        if (productId != null) {
            wrapper.eq("id", productId);
        }
        if (StringUtils.hasText(productName)) {
            wrapper.like("name", productName);
        }
        if (categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }
        if (minPrice != null && maxPrice != null) {
            wrapper.between("price", minPrice, maxPrice);
        }
        if (updateTime != null) {
            wrapper.ge("update_time", updateTime);
        }
        return baseMapper.selectPage(page, wrapper);
    }
    // 新增依赖
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserBehaviorMapper userBehaviorMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    public IPage<Product> getRecommendations(Page<Product> page, Long userId) {
        List<UserBehavior> browseRecords = userBehaviorMapper.selectList(
                new QueryWrapper<UserBehavior>()
                        .eq("user_id", userId)
                        .eq("behavior_type", 1)
        );

        // 2. 统计分类浏览频次
        Map<Long, Long> categoryViewCounts = browseRecords.stream()
                .collect(Collectors.groupingBy(
                        UserBehavior::getCategoryId,
                        Collectors.counting()
                ));

        // 3. 按浏览次数降序排序分类ID
        List<Long> sortedCategoryIds = categoryViewCounts.entrySet().stream()
                .sorted(Map.Entry.<Long, Long>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 4. 分阶段获取商品
        List<Product> result = new ArrayList<>();

        // 优先获取高频分类商品
        if (!sortedCategoryIds.isEmpty()) {
            List<Product> priorityProducts = baseMapper.selectList(
                    new QueryWrapper<Product>()
                            .in("category_id", sortedCategoryIds)
                            .eq("is_del", 0)
                            .orderByDesc("updated_at")
            );
            result.addAll(priorityProducts);
        }

        // 获取其他分类商品（排除已展示的分类）
        List<Product> otherProducts = baseMapper.selectList(
                new QueryWrapper<Product>()
                        .notIn(!sortedCategoryIds.isEmpty(), "category_id", sortedCategoryIds)
                        .eq("is_del", 0)
                        .orderByDesc("updated_at")
        );
        result.addAll(otherProducts);

        // 5. 手动分页
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        int end = Math.min(start + (int) page.getSize(), result.size());

        return new Page<Product>()
                .setRecords(result.subList(start, end))
                .setTotal(result.size())
                .setCurrent(page.getCurrent())
                .setSize(page.getSize());
    }
    @Autowired
    private ICategoryService categoryService;
    @Override
    public IPage<Product> getProductsByCategoryTree(Page<Product> page, Long categoryId) {
        // 获取所有子分类ID（包含自己）
        List<Long> categoryIds = categoryService.getAllSubCategoryIds(categoryId);

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("category_id", categoryIds)
                .eq("is_del", 0)
                .orderByDesc("updated_at");

        return baseMapper.selectPage(page, queryWrapper);
    }
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public Map<String, Object> getProductViewStats(LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> dailyData = userBehaviorMapper.selectDailyViewCounts(
                startTime, endTime, 1); // 1表示浏览行为类型

        long total = dailyData.stream()
                .mapToLong(item -> (Long) item.get("count"))
                .sum();

        return Map.of(
                "dailyData", dailyData,
                "total", total
        );
    }

    @Override
    public Map<String, Object> getProductOrderStats(LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> dailyData = orderMapper.selectDailyOrderCounts(
                startTime, endTime);

        long total = dailyData.stream()
                .mapToLong(item -> (Long) item.get("count"))
                .sum();

        return Map.of(
                "dailyData", dailyData,
                "total", total
        );
    }

    @Override
    public Map<String, Object> getProductPaymentStats(LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> dailyData = paymentMapper.selectDailyPaymentAmounts(
                startTime, endTime);

        BigDecimal total = dailyData.stream()
                .map(item -> (BigDecimal) item.get("amount"))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        return Map.of(
                "dailyData", dailyData,
                "total", total
        );
    }

}
